{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 253,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Requirement already satisfied: reportlab in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (4.1.0)\n",
      "Requirement already satisfied: yfinance in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (0.2.37)\n",
      "Requirement already satisfied: matplotlib in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (3.8.4)\n",
      "Requirement already satisfied: scrapy in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (2.11.1)\n",
      "Requirement already satisfied: sec_api in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (1.0.17)\n",
      "Requirement already satisfied: langchain in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (0.1.14)\n",
      "Requirement already satisfied: umap-learn in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (0.5.6)\n",
      "Requirement already satisfied: scikit-learn in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (1.4.1.post1)\n",
      "Requirement already satisfied: langchain_community in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (0.0.31)\n",
      "Requirement already satisfied: tiktoken in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (0.6.0)\n",
      "Requirement already satisfied: langchain-openai in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (0.1.1)\n",
      "Requirement already satisfied: langchainhub in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (0.1.15)\n",
      "Requirement already satisfied: chromadb in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (0.4.24)\n",
      "Requirement already satisfied: langchain-anthropic in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (0.1.6)\n",
      "Requirement already satisfied: sentence-transformers in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (2.6.1)\n",
      "Collecting ollama\n",
      "  Downloading ollama-0.1.8-py3-none-any.whl.metadata (3.8 kB)\n",
      "Requirement already satisfied: pillow>=9.0.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from reportlab) (10.3.0)\n",
      "Requirement already satisfied: chardet in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from reportlab) (5.2.0)\n",
      "Requirement already satisfied: pandas>=1.3.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from yfinance) (2.2.1)\n",
      "Requirement already satisfied: numpy>=1.16.5 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from yfinance) (1.26.4)\n",
      "Requirement already satisfied: requests>=2.31 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from yfinance) (2.31.0)\n",
      "Requirement already satisfied: multitasking>=0.0.7 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from yfinance) (0.0.11)\n",
      "Requirement already satisfied: lxml>=4.9.1 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from yfinance) (5.2.1)\n",
      "Requirement already satisfied: appdirs>=1.4.4 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from yfinance) (1.4.4)\n",
      "Requirement already satisfied: pytz>=2022.5 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from yfinance) (2024.1)\n",
      "Requirement already satisfied: frozendict>=2.3.4 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from yfinance) (2.4.1)\n",
      "Requirement already satisfied: peewee>=3.16.2 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from yfinance) (3.17.1)\n",
      "Requirement already satisfied: beautifulsoup4>=4.11.1 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from yfinance) (4.12.3)\n",
      "Requirement already satisfied: html5lib>=1.1 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from yfinance) (1.1)\n",
      "Requirement already satisfied: contourpy>=1.0.1 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from matplotlib) (1.2.1)\n",
      "Requirement already satisfied: cycler>=0.10 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from matplotlib) (0.12.1)\n",
      "Requirement already satisfied: fonttools>=4.22.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from matplotlib) (4.51.0)\n",
      "Requirement already satisfied: kiwisolver>=1.3.1 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from matplotlib) (1.4.5)\n",
      "Requirement already satisfied: packaging>=20.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from matplotlib) (23.2)\n",
      "Requirement already satisfied: pyparsing>=2.3.1 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from matplotlib) (3.1.2)\n",
      "Requirement already satisfied: python-dateutil>=2.7 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from matplotlib) (2.9.0)\n",
      "Requirement already satisfied: Twisted>=18.9.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from scrapy) (24.3.0)\n",
      "Requirement already satisfied: cryptography>=36.0.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from scrapy) (42.0.5)\n",
      "Requirement already satisfied: cssselect>=0.9.1 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from scrapy) (1.2.0)\n",
      "Requirement already satisfied: itemloaders>=1.0.1 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from scrapy) (1.1.0)\n",
      "Requirement already satisfied: parsel>=1.5.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from scrapy) (1.9.0)\n",
      "Requirement already satisfied: pyOpenSSL>=21.0.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from scrapy) (24.1.0)\n",
      "Requirement already satisfied: queuelib>=1.4.2 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from scrapy) (1.6.2)\n",
      "Requirement already satisfied: service-identity>=18.1.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from scrapy) (24.1.0)\n",
      "Requirement already satisfied: w3lib>=1.17.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from scrapy) (2.1.2)\n",
      "Requirement already satisfied: zope.interface>=5.1.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from scrapy) (6.2)\n",
      "Requirement already satisfied: protego>=0.1.15 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from scrapy) (0.3.1)\n",
      "Requirement already satisfied: itemadapter>=0.1.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from scrapy) (0.8.0)\n",
      "Requirement already satisfied: setuptools in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from scrapy) (68.2.2)\n",
      "Requirement already satisfied: tldextract in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from scrapy) (5.1.2)\n",
      "Requirement already satisfied: PyDispatcher>=2.0.5 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from scrapy) (2.0.7)\n",
      "Requirement already satisfied: PyYAML>=5.3 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from langchain) (6.0.1)\n",
      "Requirement already satisfied: SQLAlchemy<3,>=1.4 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from langchain) (2.0.29)\n",
      "Requirement already satisfied: aiohttp<4.0.0,>=3.8.3 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from langchain) (3.9.3)\n",
      "Requirement already satisfied: dataclasses-json<0.7,>=0.5.7 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from langchain) (0.6.4)\n",
      "Requirement already satisfied: jsonpatch<2.0,>=1.33 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from langchain) (1.33)\n",
      "Requirement already satisfied: langchain-core<0.2.0,>=0.1.37 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from langchain) (0.1.40)\n",
      "Requirement already satisfied: langchain-text-splitters<0.1,>=0.0.1 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from langchain) (0.0.1)\n",
      "Requirement already satisfied: langsmith<0.2.0,>=0.1.17 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from langchain) (0.1.40)\n",
      "Requirement already satisfied: pydantic<3,>=1 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from langchain) (2.6.4)\n",
      "Requirement already satisfied: tenacity<9.0.0,>=8.1.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from langchain) (8.2.3)\n",
      "Requirement already satisfied: scipy>=1.3.1 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from umap-learn) (1.13.0)\n",
      "Requirement already satisfied: numba>=0.51.2 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from umap-learn) (0.59.1)\n",
      "Requirement already satisfied: pynndescent>=0.5 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from umap-learn) (0.5.12)\n",
      "Requirement already satisfied: tqdm in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from umap-learn) (4.66.2)\n",
      "Requirement already satisfied: joblib>=1.2.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from scikit-learn) (1.3.2)\n",
      "Requirement already satisfied: threadpoolctl>=2.0.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from scikit-learn) (3.4.0)\n",
      "Requirement already satisfied: regex>=2022.1.18 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from tiktoken) (2023.12.25)\n",
      "Requirement already satisfied: openai<2.0.0,>=1.10.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from langchain-openai) (1.16.2)\n",
      "Requirement already satisfied: types-requests<3.0.0.0,>=2.31.0.2 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from langchainhub) (2.31.0.20240406)\n",
      "Requirement already satisfied: build>=1.0.3 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from chromadb) (1.2.1)\n",
      "Requirement already satisfied: chroma-hnswlib==0.7.3 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from chromadb) (0.7.3)\n",
      "Requirement already satisfied: fastapi>=0.95.2 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from chromadb) (0.110.1)\n",
      "Requirement already satisfied: uvicorn>=0.18.3 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from uvicorn[standard]>=0.18.3->chromadb) (0.29.0)\n",
      "Requirement already satisfied: posthog>=2.4.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from chromadb) (3.5.0)\n",
      "Requirement already satisfied: typing-extensions>=4.5.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from chromadb) (4.10.0)\n",
      "Requirement already satisfied: pulsar-client>=3.1.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from chromadb) (3.4.0)\n",
      "Requirement already satisfied: onnxruntime>=1.14.1 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from chromadb) (1.17.1)\n",
      "Requirement already satisfied: opentelemetry-api>=1.2.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from chromadb) (1.24.0)\n",
      "Requirement already satisfied: opentelemetry-exporter-otlp-proto-grpc>=1.2.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from chromadb) (1.24.0)\n",
      "Requirement already satisfied: opentelemetry-instrumentation-fastapi>=0.41b0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from chromadb) (0.45b0)\n",
      "Requirement already satisfied: opentelemetry-sdk>=1.2.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from chromadb) (1.24.0)\n",
      "Requirement already satisfied: tokenizers>=0.13.2 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from chromadb) (0.15.2)\n",
      "Requirement already satisfied: pypika>=0.48.9 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from chromadb) (0.48.9)\n",
      "Requirement already satisfied: overrides>=7.3.1 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from chromadb) (7.7.0)\n",
      "Requirement already satisfied: importlib-resources in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from chromadb) (6.4.0)\n",
      "Requirement already satisfied: grpcio>=1.58.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from chromadb) (1.62.1)\n",
      "Requirement already satisfied: bcrypt>=4.0.1 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from chromadb) (4.1.2)\n",
      "Requirement already satisfied: typer>=0.9.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from chromadb) (0.12.1)\n",
      "Requirement already satisfied: kubernetes>=28.1.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from chromadb) (29.0.0)\n",
      "Requirement already satisfied: mmh3>=4.0.1 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from chromadb) (4.1.0)\n",
      "Requirement already satisfied: orjson>=3.9.12 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from chromadb) (3.10.0)\n",
      "Requirement already satisfied: anthropic<1,>=0.23.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from langchain-anthropic) (0.23.1)\n",
      "Requirement already satisfied: defusedxml<0.8.0,>=0.7.1 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from langchain-anthropic) (0.7.1)\n",
      "Requirement already satisfied: transformers<5.0.0,>=4.32.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from sentence-transformers) (4.39.3)\n",
      "Requirement already satisfied: torch>=1.11.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from sentence-transformers) (2.2.2)\n",
      "Requirement already satisfied: huggingface-hub>=0.15.1 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from sentence-transformers) (0.22.2)\n",
      "Requirement already satisfied: httpx<0.28.0,>=0.27.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from ollama) (0.27.0)\n",
      "Requirement already satisfied: aiosignal>=1.1.2 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from aiohttp<4.0.0,>=3.8.3->langchain) (1.3.1)\n",
      "Requirement already satisfied: attrs>=17.3.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from aiohttp<4.0.0,>=3.8.3->langchain) (23.2.0)\n",
      "Requirement already satisfied: frozenlist>=1.1.1 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from aiohttp<4.0.0,>=3.8.3->langchain) (1.4.1)\n",
      "Requirement already satisfied: multidict<7.0,>=4.5 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from aiohttp<4.0.0,>=3.8.3->langchain) (6.0.5)\n",
      "Requirement already satisfied: yarl<2.0,>=1.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from aiohttp<4.0.0,>=3.8.3->langchain) (1.9.4)\n",
      "Requirement already satisfied: anyio<5,>=3.5.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from anthropic<1,>=0.23.0->langchain-anthropic) (4.3.0)\n",
      "Requirement already satisfied: distro<2,>=1.7.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from anthropic<1,>=0.23.0->langchain-anthropic) (1.9.0)\n",
      "Requirement already satisfied: sniffio in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from anthropic<1,>=0.23.0->langchain-anthropic) (1.3.1)\n",
      "Requirement already satisfied: soupsieve>1.2 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from beautifulsoup4>=4.11.1->yfinance) (2.5)\n",
      "Requirement already satisfied: pyproject_hooks in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from build>=1.0.3->chromadb) (1.0.0)\n",
      "Requirement already satisfied: colorama in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from build>=1.0.3->chromadb) (0.4.6)\n",
      "Requirement already satisfied: cffi>=1.12 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from cryptography>=36.0.0->scrapy) (1.16.0)\n",
      "Requirement already satisfied: marshmallow<4.0.0,>=3.18.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from dataclasses-json<0.7,>=0.5.7->langchain) (3.21.1)\n",
      "Requirement already satisfied: typing-inspect<1,>=0.4.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from dataclasses-json<0.7,>=0.5.7->langchain) (0.9.0)\n",
      "Requirement already satisfied: starlette<0.38.0,>=0.37.2 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from fastapi>=0.95.2->chromadb) (0.37.2)\n",
      "Requirement already satisfied: six>=1.9 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from html5lib>=1.1->yfinance) (1.16.0)\n",
      "Requirement already satisfied: webencodings in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from html5lib>=1.1->yfinance) (0.5.1)\n",
      "Requirement already satisfied: certifi in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from httpx<0.28.0,>=0.27.0->ollama) (2024.2.2)\n",
      "Requirement already satisfied: httpcore==1.* in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from httpx<0.28.0,>=0.27.0->ollama) (1.0.5)\n",
      "Requirement already satisfied: idna in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from httpx<0.28.0,>=0.27.0->ollama) (3.6)\n",
      "Requirement already satisfied: h11<0.15,>=0.13 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from httpcore==1.*->httpx<0.28.0,>=0.27.0->ollama) (0.14.0)\n",
      "Requirement already satisfied: filelock in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from huggingface-hub>=0.15.1->sentence-transformers) (3.13.3)\n",
      "Requirement already satisfied: fsspec>=2023.5.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from huggingface-hub>=0.15.1->sentence-transformers) (2024.3.1)\n",
      "Requirement already satisfied: jmespath>=0.9.5 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from itemloaders>=1.0.1->scrapy) (1.0.1)\n",
      "Requirement already satisfied: jsonpointer>=1.9 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from jsonpatch<2.0,>=1.33->langchain) (2.4)\n",
      "Requirement already satisfied: google-auth>=1.0.1 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from kubernetes>=28.1.0->chromadb) (2.29.0)\n",
      "Requirement already satisfied: websocket-client!=0.40.0,!=0.41.*,!=0.42.*,>=0.32.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from kubernetes>=28.1.0->chromadb) (1.7.0)\n",
      "Requirement already satisfied: requests-oauthlib in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from kubernetes>=28.1.0->chromadb) (2.0.0)\n",
      "Requirement already satisfied: oauthlib>=3.2.2 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from kubernetes>=28.1.0->chromadb) (3.2.2)\n",
      "Requirement already satisfied: urllib3>=1.24.2 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from kubernetes>=28.1.0->chromadb) (2.2.1)\n",
      "Requirement already satisfied: llvmlite<0.43,>=0.42.0dev0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from numba>=0.51.2->umap-learn) (0.42.0)\n",
      "Requirement already satisfied: coloredlogs in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from onnxruntime>=1.14.1->chromadb) (15.0.1)\n",
      "Requirement already satisfied: flatbuffers in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from onnxruntime>=1.14.1->chromadb) (24.3.25)\n",
      "Requirement already satisfied: protobuf in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from onnxruntime>=1.14.1->chromadb) (4.25.3)\n",
      "Requirement already satisfied: sympy in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from onnxruntime>=1.14.1->chromadb) (1.12)\n",
      "Requirement already satisfied: deprecated>=1.2.6 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from opentelemetry-api>=1.2.0->chromadb) (1.2.14)\n",
      "Requirement already satisfied: importlib-metadata<=7.0,>=6.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from opentelemetry-api>=1.2.0->chromadb) (7.0.0)\n",
      "Requirement already satisfied: googleapis-common-protos~=1.52 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from opentelemetry-exporter-otlp-proto-grpc>=1.2.0->chromadb) (1.63.0)\n",
      "Requirement already satisfied: opentelemetry-exporter-otlp-proto-common==1.24.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from opentelemetry-exporter-otlp-proto-grpc>=1.2.0->chromadb) (1.24.0)\n",
      "Requirement already satisfied: opentelemetry-proto==1.24.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from opentelemetry-exporter-otlp-proto-grpc>=1.2.0->chromadb) (1.24.0)\n",
      "Requirement already satisfied: opentelemetry-instrumentation-asgi==0.45b0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from opentelemetry-instrumentation-fastapi>=0.41b0->chromadb) (0.45b0)\n",
      "Requirement already satisfied: opentelemetry-instrumentation==0.45b0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from opentelemetry-instrumentation-fastapi>=0.41b0->chromadb) (0.45b0)\n",
      "Requirement already satisfied: opentelemetry-semantic-conventions==0.45b0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from opentelemetry-instrumentation-fastapi>=0.41b0->chromadb) (0.45b0)\n",
      "Requirement already satisfied: opentelemetry-util-http==0.45b0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from opentelemetry-instrumentation-fastapi>=0.41b0->chromadb) (0.45b0)\n",
      "Requirement already satisfied: wrapt<2.0.0,>=1.0.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from opentelemetry-instrumentation==0.45b0->opentelemetry-instrumentation-fastapi>=0.41b0->chromadb) (1.16.0)\n",
      "Requirement already satisfied: asgiref~=3.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from opentelemetry-instrumentation-asgi==0.45b0->opentelemetry-instrumentation-fastapi>=0.41b0->chromadb) (3.8.1)\n",
      "Requirement already satisfied: tzdata>=2022.7 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from pandas>=1.3.0->yfinance) (2024.1)\n",
      "Requirement already satisfied: monotonic>=1.5 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from posthog>=2.4.0->chromadb) (1.6)\n",
      "Requirement already satisfied: backoff>=1.10.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from posthog>=2.4.0->chromadb) (2.2.1)\n",
      "Requirement already satisfied: annotated-types>=0.4.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from pydantic<3,>=1->langchain) (0.6.0)\n",
      "Requirement already satisfied: pydantic-core==2.16.3 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from pydantic<3,>=1->langchain) (2.16.3)\n",
      "Requirement already satisfied: charset-normalizer<4,>=2 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from requests>=2.31->yfinance) (3.3.2)\n",
      "Requirement already satisfied: pyasn1 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from service-identity>=18.1.0->scrapy) (0.6.0)\n",
      "Requirement already satisfied: pyasn1-modules in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from service-identity>=18.1.0->scrapy) (0.4.0)\n",
      "Requirement already satisfied: greenlet!=0.4.17 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from SQLAlchemy<3,>=1.4->langchain) (3.0.3)\n",
      "Requirement already satisfied: networkx in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from torch>=1.11.0->sentence-transformers) (3.2.1)\n",
      "Requirement already satisfied: jinja2 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from torch>=1.11.0->sentence-transformers) (3.1.3)\n",
      "Requirement already satisfied: safetensors>=0.4.1 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from transformers<5.0.0,>=4.32.0->sentence-transformers) (0.4.2)\n",
      "Requirement already satisfied: automat>=0.8.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from Twisted>=18.9.0->scrapy) (22.10.0)\n",
      "Requirement already satisfied: constantly>=15.1 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from Twisted>=18.9.0->scrapy) (23.10.4)\n",
      "Requirement already satisfied: hyperlink>=17.1.1 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from Twisted>=18.9.0->scrapy) (21.0.0)\n",
      "Requirement already satisfied: incremental>=22.10.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from Twisted>=18.9.0->scrapy) (22.10.0)\n",
      "Requirement already satisfied: twisted-iocpsupport<2,>=1.0.2 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from Twisted>=18.9.0->scrapy) (1.0.4)\n",
      "Requirement already satisfied: click>=8.0.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from typer>=0.9.0->chromadb) (8.1.7)\n",
      "Requirement already satisfied: shellingham>=1.3.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from typer>=0.9.0->chromadb) (1.5.4)\n",
      "Requirement already satisfied: rich>=10.11.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from typer>=0.9.0->chromadb) (13.7.1)\n",
      "Requirement already satisfied: httptools>=0.5.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from uvicorn[standard]>=0.18.3->chromadb) (0.6.1)\n",
      "Requirement already satisfied: python-dotenv>=0.13 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from uvicorn[standard]>=0.18.3->chromadb) (1.0.1)\n",
      "Requirement already satisfied: watchfiles>=0.13 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from uvicorn[standard]>=0.18.3->chromadb) (0.21.0)\n",
      "Requirement already satisfied: websockets>=10.4 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from uvicorn[standard]>=0.18.3->chromadb) (12.0)\n",
      "Requirement already satisfied: requests-file>=1.4 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from tldextract->scrapy) (2.0.0)\n",
      "Requirement already satisfied: pycparser in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from cffi>=1.12->cryptography>=36.0.0->scrapy) (2.22)\n",
      "Requirement already satisfied: cachetools<6.0,>=2.0.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from google-auth>=1.0.1->kubernetes>=28.1.0->chromadb) (5.3.3)\n",
      "Requirement already satisfied: rsa<5,>=3.1.4 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from google-auth>=1.0.1->kubernetes>=28.1.0->chromadb) (4.9)\n",
      "Requirement already satisfied: zipp>=0.5 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from importlib-metadata<=7.0,>=6.0->opentelemetry-api>=1.2.0->chromadb) (3.17.0)\n",
      "Requirement already satisfied: markdown-it-py>=2.2.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from rich>=10.11.0->typer>=0.9.0->chromadb) (3.0.0)\n",
      "Requirement already satisfied: pygments<3.0.0,>=2.13.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from rich>=10.11.0->typer>=0.9.0->chromadb) (2.17.2)\n",
      "Requirement already satisfied: mypy-extensions>=0.3.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from typing-inspect<1,>=0.4.0->dataclasses-json<0.7,>=0.5.7->langchain) (1.0.0)\n",
      "Requirement already satisfied: humanfriendly>=9.1 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from coloredlogs->onnxruntime>=1.14.1->chromadb) (10.0)\n",
      "Requirement already satisfied: MarkupSafe>=2.0 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from jinja2->torch>=1.11.0->sentence-transformers) (2.1.5)\n",
      "Requirement already satisfied: mpmath>=0.19 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from sympy->onnxruntime>=1.14.1->chromadb) (1.3.0)\n",
      "Requirement already satisfied: pyreadline3 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from humanfriendly>=9.1->coloredlogs->onnxruntime>=1.14.1->chromadb) (3.4.1)\n",
      "Requirement already satisfied: mdurl~=0.1 in c:\\users\\boyu\\anaconda3\\envs\\py311\\lib\\site-packages (from markdown-it-py>=2.2.0->rich>=10.11.0->typer>=0.9.0->chromadb) (0.1.2)\n",
      "Downloading ollama-0.1.8-py3-none-any.whl (9.4 kB)\n",
      "Installing collected packages: ollama\n",
      "Successfully installed ollama-0.1.8\n"
     ]
    }
   ],
   "source": [
    "!pip install reportlab yfinance matplotlib scrapy sec_api langchain umap-learn scikit-learn langchain_community tiktoken langchain-openai langchainhub chromadb langchain-anthropic sentence-transformers openbb"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "metadata": {},
   "outputs": [],
   "source": [
    "import yfinance as yf\n",
    "from matplotlib import pyplot as plt\n",
    "from pandas.tseries.offsets import DateOffset\n",
    "from sec_api import ExtractorApi\n",
    "import requests\n",
    "import pandas as pd\n",
    "import json\n",
    "import numpy as np\n",
    "from openai import OpenAI\n",
    "import os\n",
    "from utils import get_earnings_transcript, Raptor\n",
    "from langchain_community.embeddings.sentence_transformer import (\n",
    "    SentenceTransformerEmbeddings,\n",
    ")\n",
    "from langchain_openai import ChatOpenAI\n",
    "from langchain_community.vectorstores import Chroma\n",
    "from langchain_core.output_parsers import StrOutputParser\n",
    "from langchain import hub\n",
    "from langchain_core.runnables import RunnablePassthrough\n",
    "from langchain_openai import OpenAIEmbeddings\n",
    "\n",
    "from openbb import obb\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Need to be done:  \n",
    "~~1. pe ratio~~  \n",
    "~~2. eps~~  \n",
    "~~3. target price~~  \n",
    "4. income growth"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 97,
   "metadata": {},
   "outputs": [],
   "source": [
    "ticker_symbol = \"TSLA\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 102,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Using OpenAI GPT\n"
     ]
    }
   ],
   "source": [
    "# define all the necessary variables\n",
    "sec_api_key = 'YOUR_SECAPI_KEY'\n",
    "os.environ[\"OPENAI_API_KEY\"] = \"YOUR_OPENAI_KEY\"\n",
    "fmp_api_key = \"YOUR_FMP_API_KEY\"\n",
    "obb.user.credentials.fmp_api_key = fmp_api_key\n",
    "USE_CACHE = True\n",
    "\n",
    "llm = \"gpt-4-turbo-preview\"\n",
    "# llm = \"qwen:1.8b\"\n",
    "\n",
    "# embd = OpenAIEmbeddings()\n",
    "# create the open-source embedding function\n",
    "embd = SentenceTransformerEmbeddings(model_name=\"all-MiniLM-L6-v2\")\n",
    "model = ChatOpenAI(temperature=0, model=llm)\n",
    "rag_helper = Raptor(model, embd)\n",
    "\n",
    "if 'gpt' in llm:\n",
    "    print(\"Using OpenAI GPT\")\n",
    "    client = OpenAI(\n",
    "        # This is the default and can be omitted\n",
    "        api_key=os.environ.get(\"OPENAI_API_KEY\"),\n",
    "    )\n",
    "else:\n",
    "    print(\"Using local LLM, make sure you have installed Ollama (https://ollama.com/download) and have it running\")\n",
    "    client = OpenAI(\n",
    "        base_url = 'http://localhost:11434/v1',\n",
    "        api_key='ollama', # required, but unused\n",
    "    )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "OBBject\n",
       "\n",
       "id: 0661870d-cba1-7731-8000-f4e086f3b086\n",
       "results: [{'date': datetime.date(2023, 4, 12), 'open': 161.22000122070312, 'high': ...\n",
       "provider: yfinance\n",
       "warnings: None\n",
       "chart: None\n",
       "extra: {'metadata': {'arguments': {'provider_choices': {'provider': 'yfinance'}, 's..."
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# openbb.stocks.ba.headlines(\"TSLA\")\n",
    "# obb.equity.price.historical(\"AAPL\", provider=\"yfinance\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 74,
   "metadata": {},
   "outputs": [],
   "source": [
    "# stock.calendar"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 75,
   "metadata": {},
   "outputs": [],
   "source": [
    "# from openbb_agents.agent import openbb_agent"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 76,
   "metadata": {},
   "outputs": [],
   "source": [
    "# result = openbb_agent(\"Who are TSLA's peers? What is their respective market cap? Return the results in _descending_ order of market cap.\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 107,
   "metadata": {},
   "outputs": [],
   "source": [
    "# \"Develop a tailored Financial Analysis Report aligned with the user's individual needs, drawing insights from the supplied reference materials. Initiate interaction with the user to obtain essential specifics and resolve any ambiguities. Iteratively refine the Financial Analysis Report through consistent evaluations using the given evaluationRubric and gather user input to ensure the end product aligns with the users expectations. You MUST FOLLOW the rules in order.\",\"role\":\"expert level accountant\",\"department\":\"finance\",\"task\":\"Create a Financial Analysis Report\",\"task_description\":\"As an expert level accountant in the finance department, your task is to create a Financial Analysis Report that provides comprehensive insights into the financial performance and health of the company. The report should be accurate, detailed, and well-structured, showcasing key financial metrics, trends, and analysis. The finished work will be used by the management team and stakeholders to make informed decisions, identify areas of improvement, and assess the overall financial position of the company. Core success factors include attention to detail, analytical skills, and the ability to effectively communicate complex financial information. The success of the report will be measured by its ability to provide actionable recommendations and contribute to the improvement of financial decision-making processes.\"\n",
    "\n",
    "class ReportAnalysis:\n",
    "    def __init__(self, ticker_symbol):\n",
    "        self.ticker_symbol = ticker_symbol\n",
    "        self.stock = yf.Ticker(ticker_symbol)\n",
    "        self.info = self.stock.info\n",
    "        self.project_dir = f\"projects/{ticker_symbol}/\"\n",
    "        self.cache_dir = f\"projects/{ticker_symbol}/cache\"\n",
    "        os.makedirs(self.project_dir, exist_ok=True)\n",
    "        os.makedirs(self.cache_dir, exist_ok=True)\n",
    "        self.extractor = ExtractorApi(sec_api_key)\n",
    "        self.report_address = self.get_sec_report_address()\n",
    "        \n",
    "        self.system_prompt = \"\"\"\n",
    "            Role: Expert Investor\n",
    "            Department: Finance\n",
    "            Primary Responsibility: Generation of Customized Financial Analysis Reports\n",
    "\n",
    "            Role Description:\n",
    "            As an Expert Investor within the finance domain, your expertise is harnessed to develop bespoke Financial Analysis Reports that cater to specific client requirements. This role demands a deep dive into financial statements and market data to unearth insights regarding a company's financial performance and stability. Engaging directly with clients to gather essential information and continuously refining the report with their feedback ensures the final product precisely meets their needs and expectations.\n",
    "\n",
    "            Key Objectives:\n",
    "\n",
    "            Analytical Precision: Employ meticulous analytical prowess to interpret financial data, identifying underlying trends and anomalies.\n",
    "            Effective Communication: Simplify and effectively convey complex financial narratives, making them accessible and actionable to non-specialist audiences.\n",
    "            Client Focus: Dynamically tailor reports in response to client feedback, ensuring the final analysis aligns with their strategic objectives.\n",
    "            Adherence to Excellence: Maintain the highest standards of quality and integrity in report generation, following established benchmarks for analytical rigor.\n",
    "            Performance Indicators:\n",
    "            The efficacy of the Financial Analysis Report is measured by its utility in providing clear, actionable insights. This encompasses aiding corporate decision-making, pinpointing areas for operational enhancement, and offering a lucid evaluation of the company's financial health. Success is ultimately reflected in the report's contribution to informed investment decisions and strategic planning.\n",
    "        \"\"\"\n",
    "    \n",
    "    def get_target_price(self):\n",
    "        # API URL\n",
    "        url = f\"https://financialmodelingprep.com/api/v4/price-target?symbol={self.ticker_symbol}?apikey={fmp_api_key}\"\n",
    "\n",
    "        # 发送GET请求\n",
    "        price_target = None\n",
    "        response = requests.get(url)\n",
    "\n",
    "        # 确保请求成功\n",
    "        if response.status_code == 200:\n",
    "            # 解析JSON数据\n",
    "            data = response.json()\n",
    "\n",
    "            price_target = data[0]['priceTarget']\n",
    "        else:\n",
    "            print(\"Failed to retrieve data:\", response.status_code)\n",
    "            \n",
    "        return price_target\n",
    "    \n",
    "    def get_stock_performance(self):\n",
    "        def fetch_stock_data(ticker, period=\"1y\"):\n",
    "            stock = yf.Ticker(ticker)\n",
    "            hist = stock.history(period=period)\n",
    "            return hist['Close']\n",
    "        \n",
    "        target_close = fetch_stock_data(self.ticker_symbol)\n",
    "        sp500_close = fetch_stock_data(\"^GSPC\")\n",
    "\n",
    "        # 计算变化率\n",
    "        company_change = (target_close - target_close.iloc[0]) / target_close.iloc[0] * 100\n",
    "        sp500_change = (sp500_close - sp500_close.iloc[0]) / sp500_close.iloc[0] * 100\n",
    "\n",
    "        # 计算额外的日期点\n",
    "        start_date = company_change.index.min()\n",
    "        four_months = start_date + DateOffset(months=4)\n",
    "        eight_months = start_date + DateOffset(months=8)\n",
    "        end_date = company_change.index.max()\n",
    "\n",
    "        # 准备绘图\n",
    "        plt.rcParams.update({'font.size': 20})  # 调整为更大的字体大小\n",
    "        plt.figure(figsize=(14, 7))\n",
    "        plt.plot(company_change.index, company_change, label=f'{self.info[\"shortName\"]} Change %', color='blue')\n",
    "        plt.plot(sp500_change.index, sp500_change, label='S&P 500 Change %', color='red')\n",
    "\n",
    "        # 设置标题和标签\n",
    "        plt.title(f'{self.info[\"shortName\"]} vs S&P 500 - Change % Over the Past Year')\n",
    "        plt.xlabel('Date')\n",
    "        plt.ylabel('Change %')\n",
    "\n",
    "        # 设置x轴刻度标签\n",
    "        plt.xticks([start_date, four_months, eight_months, end_date], \n",
    "                [start_date.strftime('%Y-%m'), \n",
    "                    four_months.strftime('%Y-%m'), \n",
    "                    eight_months.strftime('%Y-%m'), \n",
    "                    end_date.strftime('%Y-%m')])\n",
    "\n",
    "        plt.legend()\n",
    "        plt.grid(True)\n",
    "        plt.tight_layout()\n",
    "        # plt.show()\n",
    "        plot_path = f\"{self.project_dir}/stock_performance.png\"\n",
    "        plt.savefig(plot_path)\n",
    "        plt.close()\n",
    "        return plot_path\n",
    "\n",
    "    def get_pe_eps_performance(self):\n",
    "        ss = self.get_income_stmt()\n",
    "        eps = ss.loc['Diluted EPS', :]\n",
    "\n",
    "        # 获取过去一年的历史数据\n",
    "        historical_data = self.stock.history(period=\"5y\")\n",
    "\n",
    "\n",
    "        # 指定的日期，并确保它们都是UTC时区的\n",
    "        dates = pd.to_datetime(eps.index[::-1], utc=True)\n",
    "\n",
    "        # 为了确保我们能够找到最接近的股市交易日，我们将转换日期并查找最接近的日期\n",
    "        results = {}\n",
    "        for date in dates:\n",
    "            # 如果指定日期不是交易日，使用bfill和ffill找到最近的交易日股价\n",
    "            if date not in historical_data.index:\n",
    "                close_price = historical_data.asof(date)\n",
    "            else:\n",
    "                close_price = historical_data.loc[date]\n",
    "\n",
    "            results[date] = close_price['Close']\n",
    "\n",
    "        \n",
    "        pe = [p/e for p, e in zip(results.values(), eps.values[::-1])]\n",
    "        dates = eps.index[::-1]\n",
    "        eps = eps.values[::-1]\n",
    "\n",
    "        # 创建图形和轴对象\n",
    "        fig, ax1 = plt.subplots(figsize=(14, 7))\n",
    "        plt.rcParams.update({'font.size': 20})  # 调整为更大的字体大小\n",
    "\n",
    "        # 绘制市盈率\n",
    "        color = 'tab:blue'\n",
    "        ax1.set_xlabel('Date')\n",
    "        ax1.set_ylabel('PE Ratio', color=color)\n",
    "        ax1.plot(dates, pe, color=color)\n",
    "        ax1.tick_params(axis='y', labelcolor=color)\n",
    "        ax1.grid(True)\n",
    "\n",
    "        # 创建与ax1共享x轴的第二个轴对象\n",
    "        ax2 = ax1.twinx()\n",
    "        color = 'tab:red'\n",
    "        ax2.set_ylabel('EPS', color=color)  # 第二个y轴的标签\n",
    "        ax2.plot(dates, eps, color=color)\n",
    "        ax2.tick_params(axis='y', labelcolor=color)\n",
    "\n",
    "        # 设置标题和x轴标签角度\n",
    "        plt.title(f'{self.info[\"shortName\"]} PE Ratios and EPS Over the Past 4 Years')\n",
    "        plt.xticks(rotation=45)\n",
    "\n",
    "        # 设置x轴刻度标签\n",
    "        plt.xticks(dates, [d.strftime('%Y-%m') for d in dates])\n",
    "\n",
    "        plt.tight_layout()\n",
    "        # plt.show()\n",
    "        plot_path = f\"{self.project_dir}/pe_performance.png\"\n",
    "        plt.savefig(plot_path)\n",
    "        plt.close()\n",
    "        return plot_path\n",
    "    \n",
    "    def get_sec_report_address(self):\n",
    "        address_json = f\"{self.project_dir}/sec_report_address.json\"\n",
    "        if not os.path.exists(address_json):\n",
    "            endpoint = f\"https://api.sec-api.io?token={sec_api_key}\"\n",
    "\n",
    "            # The query to find 10-K filings for a specific company\n",
    "            query = {\n",
    "            \"query\": { \"query_string\": { \"query\": f\"ticker:{self.ticker_symbol} AND formType:\\\"10-K\\\"\" } },\n",
    "            \"from\": \"0\",\n",
    "            \"size\": \"1\",\n",
    "            \"sort\": [{ \"filedAt\": { \"order\": \"desc\" } }]\n",
    "            }\n",
    "\n",
    "            # Making the request to the SEC API\n",
    "            response = requests.post(endpoint, json=query)\n",
    "\n",
    "            if response.status_code == 200:\n",
    "                # Parsing the response\n",
    "                filings = response.json()['filings']\n",
    "                if filings:\n",
    "                    # Assuming the latest 10-K filing is what we want \n",
    "                    latest_10k_url = filings[0]\n",
    "                    print(f\"Latest 10-K report URL for {self.ticker_symbol}: {latest_10k_url}\")\n",
    "                else:\n",
    "                    print(f\"No 10-K filings found for {self.ticker_symbol}.\")\n",
    "            else:\n",
    "                print(\"Failed to retrieve filings from SEC API.\")\n",
    "            \n",
    "            with open(address_json, \"w\") as f:\n",
    "                json.dump(latest_10k_url, f)\n",
    "        else:\n",
    "            with open(address_json, \"r\") as f:\n",
    "                latest_10k_url = json.load(f)\n",
    "\n",
    "        return latest_10k_url['linkToFilingDetails']\n",
    "    \n",
    "    def get_key_data(self):\n",
    "        # Fetch historical market data for the past 6 months\n",
    "        hist = self.stock.history(period=\"6mo\")\n",
    "\n",
    "        # 获取其他相关信息\n",
    "        info = self.info\n",
    "        close_price = hist['Close'].iloc[-1]\n",
    "\n",
    "        # Calculate the average daily trading volume\n",
    "        avg_daily_volume_6m = hist['Volume'].mean()\n",
    "\n",
    "        # Print the result\n",
    "        # print(f\"Over the past 6 months, the average daily trading volume for {ticker_symbol} was: {avg_daily_volume_6m:.2f}\")\n",
    "        result = {\n",
    "            f\"6m avg daily val ({info['currency']}mn)\": \"{:.2f}\".format(avg_daily_volume_6m/1e6),\n",
    "            f\"Closing Price ({info['currency']})\": \"{:.2f}\".format(close_price),\n",
    "            f\"Market Cap ({info['currency']}mn)\": \"{:.2f}\".format(info['marketCap']/1e6),\n",
    "            f\"52 Week Price Range ({info['currency']})\": f\"{info['fiftyTwoWeekLow']} - {info['fiftyTwoWeekHigh']}\",\n",
    "            f\"BVPS ({info['currency']})\": info['bookValue']\n",
    "        }\n",
    "        return result\n",
    "    \n",
    "    def get_company_info(self):\n",
    "        info = self.info\n",
    "        result = {\n",
    "            \"Company Name\": info['shortName'],\n",
    "            \"Industry\": info['industry'],\n",
    "            \"Sector\": info['sector'],\n",
    "            \"Country\": info['country'],\n",
    "            \"Website\": info['website']\n",
    "        }\n",
    "        return result\n",
    "    \n",
    "    def get_income_stmt(self):\n",
    "        income_stmt = self.stock.financials\n",
    "        return income_stmt\n",
    "\n",
    "    def get_balance_sheet(self):\n",
    "        balance_sheet = self.stock.balance_sheet\n",
    "        return balance_sheet\n",
    "    \n",
    "    def get_cash_flow(self):\n",
    "        cash_flow = self.stock.cashflow\n",
    "        return cash_flow\n",
    "    \n",
    "    def get_analyst_recommendations(self):\n",
    "        recommendations = self.stock.recommendations\n",
    "        row_0 = recommendations.iloc[0, 1:]  # Exclude 'period' column\n",
    "\n",
    "        # Find the maximum voting result\n",
    "        max_votes = row_0.max()\n",
    "        majority_voting_result = row_0[row_0 == max_votes].index.tolist()\n",
    "\n",
    "        return majority_voting_result[0], max_votes\n",
    "    \n",
    "    def get_earnings(self, quarter, year):\n",
    "        earnings = get_earnings_transcript(quarter, self.ticker_symbol, year)\n",
    "        return earnings\n",
    "    \n",
    "    def get_10k_section(self, section):\n",
    "        \"\"\"\n",
    "            Get 10-K reports from SEC EDGAR\n",
    "        \"\"\"\n",
    "        if section not in [1, \"1A\", \"1B\", 2, 3, 4, 5, 6, 7, \"7A\", 8, 9, \"9A\", \"9B\", 10, 11, 12, 13, 14, 15]:\n",
    "            raise ValueError(\"Section must be in [1, 1A, 1B, 2, 3, 4, 5, 6, 7, 7A, 8, 9, 9A, 9B, 10, 11, 12, 13, 14, 15]\")\n",
    "\n",
    "        section = str(section)\n",
    "        os.makedirs(f\"{self.project_dir}/10k\", exist_ok=True)\n",
    "\n",
    "        report_name = f\"{self.project_dir}/10k/section_{section}.txt\"\n",
    "\n",
    "        if USE_CACHE and os.path.exists(report_name):\n",
    "            with open(report_name, \"r\") as f:\n",
    "                section_text = f.read()\n",
    "        else:\n",
    "            section_text = self.extractor.get_section(self.report_address, section, \"text\")\n",
    "\n",
    "            with open(report_name, \"w\") as f:\n",
    "                f.write(section_text)\n",
    "        \n",
    "        return section_text\n",
    "    \n",
    "    def get_10k_rag(self, section):\n",
    "        # Now, use all_texts to build the vectorstore with Chroma\n",
    "        vector_dir = f\"{self.cache_dir}/section_{section}_vectorstore\"\n",
    "        if USE_CACHE and os.path.exists(vector_dir):\n",
    "            vectorstore = Chroma(persist_directory=vector_dir, embedding_function=embd)\n",
    "            vectorstore.get()\n",
    "        else:\n",
    "            section_text = self.get_10k_section(section)\n",
    "            all_texts = rag_helper.text_spliter(section_text, chunk_size_tok=2000, level=1, n_levels=3)\n",
    "\n",
    "            vectorstore = Chroma.from_texts(texts=all_texts, embedding=embd, persist_directory=vector_dir)\n",
    "            vectorstore.persist()\n",
    "\n",
    "        retriever = vectorstore.as_retriever()\n",
    "\n",
    "        # Prompt\n",
    "        prompt = hub.pull(\"rlm/rag-prompt\")\n",
    "\n",
    "        # Chain\n",
    "        rag_chain = (\n",
    "            # {\"context\": retriever | format_docs, \"question\": RunnablePassthrough()}\n",
    "            {\"context\": retriever, \"question\": RunnablePassthrough()}\n",
    "            | prompt\n",
    "            | model\n",
    "            | StrOutputParser()\n",
    "        )\n",
    "\n",
    "        # Question\n",
    "        # rag_chain.invoke(\"What is the profit of the company. you should not say you don't know because all the required information is in the context\")\n",
    "        # rag_chain.invoke(\"Analyse the income statement of the company for the year 2023\")\n",
    "        return rag_chain\n",
    "    \n",
    "    def analyze_income_stmt(self):\n",
    "        cache_answer = f\"{self.project_dir}/income_stmt_analysis.txt\"\n",
    "        if USE_CACHE and os.path.exists(cache_answer):\n",
    "            with open(cache_answer, \"r\") as f:\n",
    "                answer = f.read()\n",
    "        else:\n",
    "            income_stmt = self.get_income_stmt()\n",
    "            df_string = \"Income statement:\" + income_stmt.to_string().strip()\n",
    "            \n",
    "            question = \"Embark on a thorough analysis of the company's income statement for the current fiscal year, focusing on revenue streams, cost of goods sold, operating expenses, and net income to discern the operational performance and profitability. Examine the gross profit margin to understand the cost efficiency, operating margin for operational effectiveness, and net profit margin to assess overall profitability. Compare these financial metrics against historical data to identify growth patterns, profitability trends, and operational challenges. Conclude with a strategic overview of the company's financial health, offering insights into revenue growth sustainability and potential areas for cost optimization and profit maximization in a single paragraph. Less than 130 words.\"\n",
    "\n",
    "            answer = self.ask_question(question, 7, df_string, use_rag=False)\n",
    "            with open(cache_answer, \"w\") as f:\n",
    "                f.write(answer)\n",
    "        return answer\n",
    "    \n",
    "    def analyze_balance_sheet(self):\n",
    "        cache_answer = f\"{self.project_dir}/balance_sheet_analysis.txt\"\n",
    "        if USE_CACHE and os.path.exists(cache_answer):\n",
    "            with open(cache_answer, \"r\") as f:\n",
    "                answer = f.read()\n",
    "        else:\n",
    "            balance_sheet = self.get_balance_sheet()\n",
    "            df_string = \"Balance sheet:\" + balance_sheet.to_string().strip()\n",
    "            \n",
    "            question = \"Delve into a detailed scrutiny of the company's balance sheet for the most recent fiscal year, pinpointing the structure of assets, liabilities, and shareholders' equity to decode the firm's financial stability and operational efficiency. Focus on evaluating the liquidity through current assets versus current liabilities, the solvency via long-term debt ratios, and the equity position to gauge long-term investment potential. Contrast these metrics with previous years' data to highlight financial trends, improvements, or deteriorations. Finalize with a strategic assessment of the company's financial leverage, asset management, and capital structure, providing insights into its fiscal health and future prospects in a single paragraph. Less than 130 words.\"\n",
    "\n",
    "            answer = self.ask_question(question, 7, df_string, use_rag=False)\n",
    "            with open(cache_answer, \"w\") as f:\n",
    "                f.write(answer)\n",
    "        return answer\n",
    "    \n",
    "    def analyze_cash_flow(self):\n",
    "        cache_answer = f\"{self.project_dir}/cash_flow_analysis.txt\"\n",
    "        if USE_CACHE and os.path.exists(cache_answer):\n",
    "            with open(cache_answer, \"r\") as f:\n",
    "                answer = f.read()\n",
    "        else:\n",
    "            cash_flow = self.get_cash_flow()\n",
    "            df_string = \"Balance sheet:\" + cash_flow.to_string().strip()\n",
    "            \n",
    "            question = \"Dive into a comprehensive evaluation of the company's cash flow for the latest fiscal year, focusing on cash inflows and outflows across operating, investing, and financing activities. Examine the operational cash flow to assess the core business profitability, scrutinize investing activities for insights into capital expenditures and investments, and review financing activities to understand debt, equity movements, and dividend policies. Compare these cash movements to prior periods to discern trends, sustainability, and liquidity risks. Conclude with an informed analysis of the company's cash management effectiveness, liquidity position, and potential for future growth or financial challenges in a single paragraph. Less than 130 words.\"\n",
    "\n",
    "            answer = self.ask_question(question, 7, df_string, use_rag=False)\n",
    "            with open(cache_answer, \"w\") as f:\n",
    "                f.write(answer)\n",
    "        return answer\n",
    "    \n",
    "    def financial_summarization(self):\n",
    "        income_stmt_analysis = self.analyze_income_stmt()\n",
    "        balance_sheet_analysis = self.analyze_balance_sheet()\n",
    "        cash_flow_analysis = self.analyze_cash_flow()\n",
    "        \n",
    "        cache_answer = f\"{self.project_dir}/financial_summarization.txt\"\n",
    "        if USE_CACHE and os.path.exists(cache_answer):\n",
    "            with open(cache_answer, \"r\") as f:\n",
    "                answer = f.read()\n",
    "        else:\n",
    "            question = f\"Income statement analysis: {income_stmt_analysis}, \\\n",
    "            Balance sheet analysis: {balance_sheet_analysis}, \\\n",
    "            Cash flow analysis: {cash_flow_analysis}, \\\n",
    "            Synthesize the findings from the in-depth analysis of the income statement, balance sheet, and cash flow for the latest fiscal year. Highlight the core insights regarding the company's operational performance, financial stability, and cash management efficiency. Discuss the interrelations between revenue growth, cost management strategies, and their impact on profitability as revealed by the income statement. Incorporate the balance sheet's insights on financial structure, liquidity, and solvency to provide a comprehensive view of the company's financial health. Merge these with the cash flow analysis to illustrate the company's liquidity position, investment activities, and financing strategies. Conclude with a holistic assessment of the company's fiscal health, identifying strengths, potential risks, and strategic opportunities for growth and stability. Offer recommendations to address identified challenges and capitalize on the opportunities to enhance shareholder value in a single paragraph. Less than 150 words.\"\n",
    "\n",
    "            answer = self.ask_question(question, 7, use_rag=False)\n",
    "            with open(cache_answer, \"w\") as f:\n",
    "                f.write(answer)\n",
    "        return {\"Income Statement Analysis\": income_stmt_analysis, \"Balance Sheet Analysis\": balance_sheet_analysis, \"Cash Flow Analysis\": cash_flow_analysis, \"Financial Summary\": answer}\n",
    "\n",
    "\n",
    "    def ask_question(self, question, section, table_str=None, use_rag=False):\n",
    "        if use_rag:\n",
    "            rag_chain = self.get_10k_rag(section)\n",
    "            if table_str:\n",
    "                prompt = f\"{self.system_prompt}\\n\\n{table_str}\\n\\nQuestion: {question}\"\n",
    "            else:\n",
    "                prompt = f\"{self.system_prompt}\\n\\nQuestion: {question}\"\n",
    "            answer = rag_chain.invoke(prompt)\n",
    "        else:\n",
    "            # 发送请求给OpenAI API使用指定的模型\n",
    "            section_text = self.get_10k_section(7)\n",
    "            if table_str:\n",
    "                prompt = f\"{self.system_prompt}\\n\\n{table_str}\\n\\nResource: {section_text}\\n\\nQuestion: {question}\"\n",
    "            else:\n",
    "                prompt = f\"{self.system_prompt}\\n\\nResource: {section_text}\\n\\nQuestion: {question}\"\n",
    "            \n",
    "            chat_completion = client.chat.completions.create(\n",
    "                messages=[\n",
    "                    {\n",
    "                        \"role\": \"user\",\n",
    "                        \"content\": prompt.strip(),\n",
    "                    }\n",
    "                ],\n",
    "                # model=\"gpt-4-1106-preview\",\n",
    "                model=llm,\n",
    "                temperature = 0,\n",
    "                max_tokens = 500,\n",
    "                # response_format={ \"type\": \"json_object\" },\n",
    "            )\n",
    "            answer = chat_completion.choices[0].message.content\n",
    "\n",
    "        return answer\n",
    "\n",
    "\n",
    "ra = ReportAnalysis(ticker_symbol)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 99,
   "metadata": {},
   "outputs": [],
   "source": [
    "answer = ra.financial_summarization()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Resources to understand the financial report\n",
    "1. income statement: https://online.hbs.edu/blog/post/income-statement-analysis\n",
    "2. balance sheet: https://online.hbs.edu/blog/post/how-to-read-a-balance-sheet\n",
    "3. cash flow statement: https://online.hbs.edu/blog/post/how-to-read-a-cash-flow-statement\n",
    "4. Annual report: https://online.hbs.edu/blog/post/how-to-read-an-annual-report\n",
    "\n",
    "An annual report typically consists of:\n",
    "1. Letters to shareholders: These documents provide a broad overview of the company’s activities and performance over the course of the year, as well as a reflection on its general business environment. An annual report usually includes a shareholder letter from the CEO or president, and may also contain letters from other key figures, such as the CFO.\n",
    "2. [section 7] Management’s discussion and analysis (MD&A): This is a detailed analysis of the company’s performance, as conducted by its executives.\n",
    "3. [section 8] Audited financial statements: These are financial documents that detail the company’s financial performance. Commonly included statements include balance sheets, cash flow statements, income statements, and equity statements.\n",
    "4. [section 8] A summary of financial data: This refers to any notes or discussions that are pertinent to the financial statements listed above.\n",
    "5. [section 8] Auditor’s report: This report describes whether the company has complied with generally accepted accounting principles (GAAP) in preparing its financial statements.\n",
    "6. Accounting policies: This is an overview of the policies the company’s leadership team relied upon in preparing the annual report and financial statements.\n",
    "\n",
    "\n",
    "Answer the following questions:\n",
    "1. Whether it’s able to pay debts as they come due\n",
    "2. Its profits and/or losses year over year\n",
    "3. If and how it’s grown over time\n",
    "4. What it requires to maintain or expand its business\n",
    "5. Operational expenses compared to generated revenues"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Build the pdf Report\n",
    "\n",
    "format: https://docs.reportlab.com/rml/tutorials/fund-reports-json-to-pdf/"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 100,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\Boyu\\AppData\\Local\\Temp\\ipykernel_25956\\708270834.py:185: FutureWarning: DataFrame.applymap has been deprecated. Use DataFrame.map instead.\n",
      "  df = df.applymap(convert_if_money)\n",
      "C:\\Users\\Boyu\\AppData\\Local\\Temp\\ipykernel_25956\\708270834.py:203: FutureWarning: DataFrame.applymap has been deprecated. Use DataFrame.map instead.\n",
      "  df = df.applymap(convert_if_money)\n"
     ]
    }
   ],
   "source": [
    "from reportlab.lib import colors\n",
    "from reportlab.lib import pagesizes\n",
    "from reportlab.platypus import SimpleDocTemplate, Frame, Paragraph, Image, PageTemplate, FrameBreak, Spacer, Table, TableStyle, NextPageTemplate, PageBreak\n",
    "from reportlab.lib.units import inch\n",
    "from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle\n",
    "from reportlab.lib.enums import TA_CENTER, TA_JUSTIFY, TA_LEFT\n",
    "\n",
    "\n",
    "# 2. 创建PDF并插入图像\n",
    "# 页面设置\n",
    "page_width, page_height = pagesizes.A4\n",
    "left_column_width = page_width * 2/3\n",
    "right_column_width = page_width - left_column_width\n",
    "margin = 4\n",
    "\n",
    "# 创建PDF文档路径\n",
    "pdf_path = os.path.join(ra.project_dir, f\"{ticker_symbol}_report.pdf\")\n",
    "doc = SimpleDocTemplate(pdf_path, pagesize=pagesizes.A4)\n",
    "\n",
    "# 定义两个栏位的Frame\n",
    "frame_left = Frame(margin, margin, left_column_width-margin*2, page_height-margin*2, id='left')\n",
    "frame_right = Frame(left_column_width, margin, right_column_width-margin*2, page_height-margin*2, id='right')\n",
    "\n",
    "# single_frame = Frame(margin, margin, page_width-margin*2, page_height-margin*2, id='single')\n",
    "# single_column_layout = PageTemplate(id='OneCol', frames=[single_frame])\n",
    "\n",
    "left_column_width_p2 = (page_width-margin*3) // 2\n",
    "right_column_width_p2 = left_column_width_p2\n",
    "frame_left_p2 = Frame(margin, margin, left_column_width_p2-margin*2, page_height-margin*2, id='left')\n",
    "frame_right_p2 = Frame(left_column_width_p2, margin, right_column_width_p2-margin*2, page_height-margin*2, id='right')\n",
    "\n",
    "# 创建PageTemplate，并添加到文档\n",
    "page_template = PageTemplate(id='TwoColumns', frames=[frame_left, frame_right])\n",
    "page_template_p2 = PageTemplate(id='TwoColumns_p2', frames=[frame_left_p2, frame_right_p2])\n",
    "doc.addPageTemplates([page_template, page_template_p2])\n",
    "\n",
    "styles = getSampleStyleSheet()\n",
    "\n",
    "# 自定义样式\n",
    "custom_style = ParagraphStyle(\n",
    "    name=\"Custom\",\n",
    "    parent=styles['Normal'],\n",
    "    fontName=\"Helvetica\",\n",
    "    fontSize=10,\n",
    "    # leading=15,\n",
    "    alignment=TA_JUSTIFY,\n",
    ")\n",
    "\n",
    "title_style = ParagraphStyle(\n",
    "    name=\"TitleCustom\",\n",
    "    parent=styles['Title'],\n",
    "    fontName=\"Helvetica-Bold\",\n",
    "    fontSize=16,\n",
    "    leading=20,\n",
    "    alignment=TA_LEFT,\n",
    "    spaceAfter=10,\n",
    ")\n",
    "\n",
    "subtitle_style = ParagraphStyle(\n",
    "    name=\"Subtitle\",\n",
    "    parent=styles['Heading2'],\n",
    "    fontName=\"Helvetica-Bold\",\n",
    "    fontSize=14,\n",
    "    leading=12,\n",
    "    alignment=TA_LEFT,\n",
    "    spaceAfter=6,\n",
    ")\n",
    "\n",
    "# 准备左栏和右栏内容\n",
    "content = []\n",
    "# 标题\n",
    "content.append(Paragraph(f\"Equity Research Report: {ra.get_company_info()['Company Name']}\", title_style))\n",
    "\n",
    "# 子标题\n",
    "content.append(Paragraph(\"Income Statement Analysis\", subtitle_style))\n",
    "content.append(Paragraph(answer['Income Statement Analysis'], custom_style))\n",
    "\n",
    "content.append(Paragraph(\"Balance Sheet Analysis\", subtitle_style))\n",
    "content.append(Paragraph(answer['Balance Sheet Analysis'], custom_style))\n",
    "\n",
    "content.append(Paragraph(\"Cashflow Analysis\", subtitle_style))\n",
    "content.append(Paragraph(answer['Cash Flow Analysis'], custom_style))\n",
    "\n",
    "content.append(Paragraph(\"Summarization\", subtitle_style))\n",
    "content.append(Paragraph(answer['Financial Summary'], custom_style))\n",
    "\n",
    "\n",
    "content.append(FrameBreak())  # 用于从左栏跳到右栏\n",
    "\n",
    "table_style = TableStyle([\n",
    "    ('BACKGROUND', (0, 0), (-1, -1), colors.white),\n",
    "    ('BACKGROUND', (0, 0), (-1, 0), colors.white),\n",
    "    ('FONT', (0, 0), (-1, -1), 'Helvetica', 8),\n",
    "    ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold', 12),\n",
    "    ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),\n",
    "    # 第一列左对齐\n",
    "    ('ALIGN', (0,1), (0,-1), 'LEFT'),\n",
    "    # 第二列右对齐\n",
    "    ('ALIGN', (1,1), (1,-1), 'RIGHT'),\n",
    "    # 标题栏下方添加横线\n",
    "    ('LINEBELOW', (0,0), (-1,0), 2, colors.black),\n",
    "])\n",
    "full_length = right_column_width-2*margin\n",
    "\n",
    "rating, _ = ra.get_analyst_recommendations()\n",
    "target_price = ra.get_target_price()\n",
    "if target_price is not None:\n",
    "    data = [\n",
    "        [\"Rating:\", rating.upper()],\n",
    "        [\"Target Price:\", f\"{target_price:.2f}\"]\n",
    "    ]\n",
    "else:\n",
    "    data = [[\"Rating:\", rating.upper()]]\n",
    "col_widths = [full_length//3*2, full_length//3]\n",
    "table = Table(data, colWidths=col_widths)\n",
    "table.setStyle(table_style)\n",
    "content.append(table)\n",
    "\n",
    "# content.append(Paragraph(\"\", custom_style))\n",
    "content.append(Spacer(1, 0.15*inch))\n",
    "key_data = ra.get_key_data()\n",
    "# 表格数据\n",
    "data = [[\"Key data\", \"\"]]\n",
    "data += [\n",
    "    [k, v] for k, v in key_data.items()\n",
    "]\n",
    "col_widths = [full_length//3*2, full_length//3]\n",
    "table = Table(data, colWidths=col_widths)\n",
    "table.setStyle(table_style)\n",
    "content.append(table)\n",
    "\n",
    "\n",
    "# 将Matplotlib图像添加到右栏\n",
    "\n",
    "# 历史股价\n",
    "data = [[\"Share Performance\"]]\n",
    "col_widths = [full_length]\n",
    "table = Table(data, colWidths=col_widths)\n",
    "table.setStyle(table_style)\n",
    "content.append(table)\n",
    "\n",
    "plot_path = ra.get_stock_performance()\n",
    "width = right_column_width\n",
    "height = width//2\n",
    "content.append(Image(plot_path, width=width, height=height))\n",
    "\n",
    "# 历史PE和EPS\n",
    "data = [[\"PE & EPS\"]]\n",
    "col_widths = [full_length]\n",
    "table = Table(data, colWidths=col_widths)\n",
    "table.setStyle(table_style)\n",
    "content.append(table)\n",
    "\n",
    "plot_path = ra.get_pe_eps_performance()\n",
    "width = right_column_width\n",
    "height = width//2\n",
    "content.append(Image(plot_path, width=width, height=height))\n",
    "\n",
    "\n",
    "# 开始新的一页\n",
    "content.append(NextPageTemplate('TwoColumns_p2'))\n",
    "content.append(PageBreak())\n",
    "\n",
    "table_style2 = TableStyle([\n",
    "    ('BACKGROUND', (0, 0), (-1, -1), colors.white),\n",
    "    ('BACKGROUND', (0, 0), (-1, 0), colors.white),\n",
    "    ('FONT', (0, 0), (-1, -1), 'Helvetica', 6),\n",
    "    ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold', 10),\n",
    "    ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),\n",
    "    # 第一列左对齐\n",
    "    ('ALIGN', (0,1), (0,-1), 'LEFT'),\n",
    "    # 第二列右对齐\n",
    "    ('ALIGN', (1,1), (1,-1), 'RIGHT'),\n",
    "    # 标题栏下方添加横线\n",
    "    ('LINEBELOW', (0,0), (-1,0), 2, colors.black),\n",
    "    # 表格最下方添加横线\n",
    "    ('LINEBELOW', (0,-1), (-1,-1), 2, colors.black),\n",
    "])\n",
    "\n",
    "\n",
    "# 第二页及之后内容，使用单栏布局\n",
    "df = ra.get_income_stmt()\n",
    "df = df[df.columns[:3]]\n",
    "def convert_if_money(value):\n",
    "    if np.abs(value) >= 1000000:\n",
    "        return value / 1000000\n",
    "    else:\n",
    "        return value\n",
    "\n",
    "# 应用转换函数到DataFrame的每列\n",
    "df = df.applymap(convert_if_money)\n",
    "\n",
    "df.columns = [col.strftime('%Y') for col in df.columns]\n",
    "df.reset_index(inplace=True)\n",
    "currency = ra.info['currency']\n",
    "df.rename(columns={'index': f'FY ({currency} mn)'}, inplace=True)  # 可选：重命名索引列为“序号”\n",
    "table_data = [[\"Income Statement\"]]\n",
    "table_data += [df.columns.to_list()] + df.values.tolist()\n",
    "\n",
    "table = Table(table_data)\n",
    "table.setStyle(table_style2)\n",
    "content.append(table)\n",
    "\n",
    "content.append(FrameBreak())  # 用于从左栏跳到右栏\n",
    "\n",
    "df = ra.get_cash_flow()\n",
    "df = df[df.columns[:3]]\n",
    "\n",
    "df = df.applymap(convert_if_money)\n",
    "\n",
    "df.columns = [col.strftime('%Y') for col in df.columns]\n",
    "df.reset_index(inplace=True)\n",
    "currency = ra.info['currency']\n",
    "df.rename(columns={'index': f'FY ({currency} mn)'}, inplace=True)  # 可选：重命名索引列为“序号”\n",
    "table_data = [[\"Cash Flow Sheet\"]]\n",
    "table_data += [df.columns.to_list()] + df.values.tolist()\n",
    "\n",
    "table = Table(table_data)\n",
    "table.setStyle(table_style2)\n",
    "content.append(table)\n",
    "# content.append(Paragraph('This is a single column on the second page', custom_style))\n",
    "# content.append(Spacer(1, 0.2*inch))\n",
    "# content.append(Paragraph('More content in the single column.', custom_style))\n",
    "\n",
    "# 构建PDF文档\n",
    "doc.build(content)\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
